const pool = require('../config/database');

class HospitalizationHistoryModel {
  /**
   * 创建住院史记录
   * @param {Object} historyData - 住院史数据
   * @returns {Promise<Object>} 创建的住院史记录
   */
  static async create(historyData) {
    const connection = await pool.getConnection();
    
    try {
      await connection.beginTransaction();
      
      const fields = Object.keys(historyData);
      const values = Object.values(historyData);
      const placeholders = fields.map(() => '?').join(', ');
      
      const sql = `
        INSERT INTO jktj_hospitalization_history (${fields.join(', ')})
        VALUES (${placeholders})
      `;
      
      const [result] = await connection.execute(sql, values);
      
      await connection.commit();
      
      return {
        id: result.insertId,
        ...historyData
      };
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  }

  /**
   * 批量创建住院史记录
   * @param {Array<Object>} historyList - 住院史数据数组
   * @returns {Promise<Array>} 创建的住院史记录数组
   */
  static async createBatch(historyList) {
    if (!historyList || historyList.length === 0) {
      return [];
    }

    const connection = await pool.getConnection();
    const results = [];
    
    try {
      await connection.beginTransaction();
      
      for (const historyData of historyList) {
        const fields = Object.keys(historyData);
        const values = Object.values(historyData);
        const placeholders = fields.map(() => '?').join(', ');
        
        const sql = `
          INSERT INTO jktj_hospitalization_history (${fields.join(', ')})
          VALUES (${placeholders})
        `;
        
        const [result] = await connection.execute(sql, values);
        
        results.push({
          id: result.insertId,
          ...historyData
        });
      }
      
      await connection.commit();
      return results;
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  }

  /**
   * 根据体检ID获取住院史记录列表
   * @param {number} tjId - 体检ID
   * @returns {Promise<Array>} 住院史记录列表
   */
  static async findByTjId(tjId) {
    const sql = 'SELECT * FROM jktj_hospitalization_history WHERE tj_id = ? ORDER BY ryrq DESC';
    const [rows] = await pool.execute(sql, [tjId]);
    return rows;
  }

  /**
   * 根据ID获取住院史记录
   * @param {number} id - 住院史记录ID
   * @returns {Promise<Object>} 住院史记录
   */
  static async findById(id) {
    const sql = 'SELECT * FROM jktj_hospitalization_history WHERE id = ?';
    const [rows] = await pool.execute(sql, [id]);
    return rows[0] || null;
  }

  /**
   * 更新住院史记录
   * @param {number} id - 住院史记录ID
   * @param {Object} updateData - 更新数据
   * @returns {Promise<boolean>} 更新结果
   */
  static async update(id, updateData) {
    const fields = Object.keys(updateData);
    const values = Object.values(updateData);
    const setClause = fields.map(field => `${field} = ?`).join(', ');
    
    const sql = `UPDATE jktj_hospitalization_history SET ${setClause} WHERE id = ?`;
    const [result] = await pool.execute(sql, [...values, id]);
    
    return result.affectedRows > 0;
  }

  /**
   * 删除住院史记录
   * @param {number} id - 住院史记录ID
   * @returns {Promise<boolean>} 删除结果
   */
  static async delete(id) {
    const sql = 'DELETE FROM jktj_hospitalization_history WHERE id = ?';
    const [result] = await pool.execute(sql, [id]);
    return result.affectedRows > 0;
  }

  /**
   * 根据体检ID删除所有住院史记录
   * @param {number} tjId - 体检ID
   * @returns {Promise<boolean>} 删除结果
   */
  static async deleteByTjId(tjId) {
    const sql = 'DELETE FROM jktj_hospitalization_history WHERE tj_id = ?';
    const [result] = await pool.execute(sql, [tjId]);
    return result.affectedRows > 0;
  }

  /**
   * 批量获取多个体检的住院史记录
   * @param {Array<number>} tjIds - 体检ID数组
   * @returns {Promise<Array>} 住院史记录数组
   */
  static async findByTjIds(tjIds) {
    if (!tjIds || tjIds.length === 0) {
      return [];
    }
    
    const placeholders = tjIds.map(() => '?').join(', ');
    const sql = `
      SELECT * FROM jktj_hospitalization_history 
      WHERE tj_id IN (${placeholders}) 
      ORDER BY tj_id, ryrq DESC
    `;
    const [rows] = await pool.execute(sql, tjIds);
    return rows;
  }

  /**
   * 获取指定时间范围内的住院史记录
   * @param {number} tjId - 体检ID
   * @param {Date} startDate - 开始日期
   * @param {Date} endDate - 结束日期
   * @returns {Promise<Array>} 住院史记录列表
   */
  static async findByDateRange(tjId, startDate, endDate) {
    const sql = `
      SELECT * FROM jktj_hospitalization_history 
      WHERE tj_id = ? AND ryrq >= ? AND ryrq <= ?
      ORDER BY ryrq DESC
    `;
    const [rows] = await pool.execute(sql, [tjId, startDate, endDate]);
    return rows;
  }
}

module.exports = HospitalizationHistoryModel;